﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Risk.Services;
using Risk.Model;
using Site.Models;

namespace Site.Controllers
{
    public class OpenGamesController : Controller
    {
        //
        // GET: /OpenGames/

        public ActionResult Index()
        {
            if (Session["Username"] == null)
                return RedirectToAction("Index", "Home");
            return View(new OpenGamesDTO(Convert.ToString(Session["Username"])));
        }

        public ActionResult CreateGame()
        {
            DatabaseManager.CreatePlayer(DatabaseManager.CreateGame(), Convert.ToString(Session["Username"]), true);
            return View("Index", new OpenGamesDTO(Convert.ToString(Session["Username"])));
        }

        public ActionResult JoinGame(int gameId)
        {
            var game = new GameDTO(gameId);
            string username = Convert.ToString(Session["Username"]);
            if (game.Players.Count >= 6)
                ViewBag.Message = "Game is full";
            else if (DatabaseManager.PlayerIsIngame(username, game.Id))
                ViewBag.Message = "You have already joined that game";
            else
            {
                DatabaseManager.CreatePlayer(game.Id, username);
            }
            return View("Index", new OpenGamesDTO(Convert.ToString(Session["Username"])));
            
        }
        private static readonly List<String> Colors = new List<string> { "Chartreuse", "Crimson", "Coral", "DeepSkyBlue", "Gold", "DarkSlateBlue" }; 
        public ActionResult StartGame(int gameId)
        {
            string username = Convert.ToString(Session["Username"]);
            if (DatabaseManager.IsCreatorOfGame(username, gameId))
            {
                var game = new GameDTO(gameId);


                for (int i = 0; i < game.Players.Count; i++)
                    game.Players[i].Color = Colors[i];


                var riskGame = new Game (DatabaseManager.GetPlayers(gameId));
                riskGame.InitializeGame();
                DatabaseManager.LoadGameIntoDatabase(riskGame, gameId);
            }
            else
            {
                ViewBag.Message = "You are not the creator of this game";
                return View("Index", new OpenGamesDTO(Convert.ToString(Session["Username"])));
            }
            return RedirectToAction("Index", "ActiveGames");
        }
    }
}
